﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace LagrangePlynomial
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }



        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            Random random = new Random();
            
            int width = pictureBox1.Width;
            int height = pictureBox1.Height;
            Font f = Font;

            Graphics g = e.Graphics;
            
            int x1 = random.Next(0, width/2);
            int x2 = random.Next(0, width/2);
            int x3 = random.Next(0, width/2);
            int y1 = random.Next(0, height/2);
            int y2 = random.Next(0, height/2);
            int y3 = random.Next(0, height/2);
            


            int xMin;
            int xMax;

            if (x1 > x2 && x1 > x3)
                xMax = x1;
            else if (x2 > x1 && x2 > x3)
                xMax = x2;
            else xMax = x3;

            if (x1 < x2 && x1 < x3)
                xMin = x1;
            else if (x2 < x1 && x2 < x3)
                xMin = x2;
            else xMin = x3;

            

            bool firstIteration = true;
            float lastX = 0;
            float lastY = 0;

                for (float x = xMin; x <= xMax; x += (float)0.1)
                {
                    float newX;
                    float newY;
                    newX = x;
                    newY = F(x, x1, x2, x3, y1) + F(x, x2, x1, x3, y2) + F(x, x3, x1, x2, y3);

                    if (firstIteration)
                    {
                        lastX = newX;
                        lastY = newY;
                        firstIteration = false;
                        continue;
                    }

                    g.DrawLine(Pens.Magenta, lastX, lastY, newX, newY);

                    lastX = newX;
                    lastY = newY;


                    g.DrawLine(Pens.Magenta, x1, y1, x2, y2);
                    g.DrawLine(Pens.Magenta, x2, y2, x3, y3);
            }

        }



        private float F(float x, int x1, int x2, int x3,int y)
        {
            float p;
            p = ((x-x2)*(x-x3))/((x1-x2)*(x1-x3))*y;
            return p;

        }

        #region bull shit
        private void Form1_Resize(object sender, EventArgs e)
        {
            pictureBox1.Width = Width;
            pictureBox1.Height = Height;

            pictureBox1.Invalidate();
        }
        #endregion
    }
}
